package com.project.school_flate.serviceimpl.com;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.project.school_flate.dto.com.ComSchoolDto;
import com.project.school_flate.entity.com.ComSchool;
import com.project.school_flate.entity.com.ComSchool;
import com.project.school_flate.entity.order.table.OrderTakeawayTableDef;
import com.project.school_flate.entity.table.com.ComAdminTable;
import com.project.school_flate.entity.table.com.ComSchoolTable;
import com.project.school_flate.mapper.com.ComSchoolMapper;
import com.project.school_flate.mapper.order.OrderTakeawayMapper;
import com.project.school_flate.service.com.ComSchoolService;
import com.project.school_flate.util.DistanceUtil;
import com.project.school_flate.util.PoToDTO;
import com.project.school_flate.util.Result.Result;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

/**
 *  服务层实现。
 *
 * @author 马维健
 * @since 2024/1/2
 */
@Service
public class ComSchoolServiceImpl extends ServiceImpl<ComSchoolMapper, ComSchool> implements ComSchoolService {

    @Autowired
    private ComSchoolMapper oComSchoolMapper;

    @Autowired
    private OrderTakeawayMapper oOrderTakeawayMapper;

    /**
     * 获取校园
     * @param oComSchoolDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getComSchool(ComSchoolDto oComSchoolDto) throws Exception {
        List<ComSchool> oComSchoolList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(ComSchoolTable.COM_SCHOOL.STATE.eq(1));
        queryWrapper.orderBy("create_time desc");
        //是否分页
        if(oComSchoolDto.getPage() != null && oComSchoolDto.getLimit() != null){
            Page<ComSchool> ComSchoolPage = oComSchoolMapper.paginateWithRelations(oComSchoolDto.getPage(),oComSchoolDto.getLimit(),queryWrapper);
            oComSchoolList = ComSchoolPage.getRecords();
            total = ComSchoolPage.getTotalRow();
        }else{
            oComSchoolList = oComSchoolMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oComSchoolList.size();
        }
        //PoToDto
        List<ComSchoolDto> oComSchoolDtoList = (List<ComSchoolDto>) PoToDTO.poToDtoList(oComSchoolList,new ComSchoolDto());
        return Result.ok(oComSchoolDtoList,total);
    }

    /**
     * 添加校园
     * @param oComSchoolDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result addComSchool(ComSchoolDto oComSchoolDto) throws Exception {
        ComSchool oComSchool = new ComSchool();
        PoToDTO.poToDto(oComSchoolDto,oComSchool);
        if(oComSchoolMapper.insert(oComSchool) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("添加校园失败");
        }
        return Result.ok("添加校园成功");
    }

    /**
     * 修改校园
     * @param oComSchoolDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result updateComSchool(ComSchoolDto oComSchoolDto) throws Exception {
        ComSchool oComSchool = new ComSchool();
        PoToDTO.poToDto(oComSchoolDto,oComSchool);
        if(oComSchoolMapper.update(oComSchool) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("修改校园失败");
        }
        return Result.ok("修改校园成功");
    }

    /**
     * 冻结校园
     * @param oComSchoolDto
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Result freezeComSchool(ComSchoolDto oComSchoolDto) throws Exception {
        ComSchool oComSchool = new ComSchool();
        PoToDTO.poToDto(oComSchoolDto,oComSchool);
        //判断是否还有订单未完成
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.SCHOOL_ID.eq(oComSchool.getId()));
        queryWrapper.where(OrderTakeawayTableDef.ORDER_TAKEAWAY.PAY_STATE.notIn(2,4,6));
        if(CollectionUtils.isNotEmpty(oOrderTakeawayMapper.selectListByQuery(queryWrapper))){
            return Result.error("还有订单未完成");
        }
        oComSchool.setState(0);
        if(oComSchoolMapper.update(oComSchool) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("冻结校园失败");
        }
        return Result.ok("冻结校园成功");
    }

    /**
     * 获取校园（后台）
     * @param oComSchoolDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getComSchoolBack(ComSchoolDto oComSchoolDto) throws Exception {
        List<ComSchool> oComSchoolList = new ArrayList<>();
        long total = 0;
        QueryWrapper queryWrapper = new QueryWrapper();
        //判断是否传入名字
        if(StringUtils.isNotBlank(oComSchoolDto.getName())){
            queryWrapper.where(ComSchoolTable.COM_SCHOOL.NAME.like(oComSchoolDto.getName()));
        }
        queryWrapper.orderBy("create_time desc");
        //是否分页
        if(oComSchoolDto.getPage() != null && oComSchoolDto.getLimit() != null){
            Page<ComSchool> ComSchoolPage = oComSchoolMapper.paginateWithRelations(oComSchoolDto.getPage(),oComSchoolDto.getLimit(),queryWrapper);
            oComSchoolList = ComSchoolPage.getRecords();
            total = ComSchoolPage.getTotalRow();
        }else{
            oComSchoolList = oComSchoolMapper.selectListWithRelationsByQuery(queryWrapper);
            total = oComSchoolList.size();
        }
        //PoToDto
        List<ComSchoolDto> oComSchoolDtoList = (List<ComSchoolDto>) PoToDTO.poToDtoList(oComSchoolList,new ComSchoolDto());
        return Result.ok(oComSchoolDtoList,total);
    }

    /**
     * 解冻校园
     * @param oComSchoolDto
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public Result thawComSchool(ComSchoolDto oComSchoolDto) throws Exception {
        ComSchool oComSchool = new ComSchool();
        PoToDTO.poToDto(oComSchoolDto,oComSchool);
        oComSchool.setState(1);
        if(oComSchoolMapper.update(oComSchool) == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("解冻校园失败");
        }
        return Result.ok("解冻校园成功");
    }

    /**
     * 获取用户定位校园
     * @param oComSchoolDto
     * @return
     * @throws Exception
     */
    @Override
    public Result getUserLocationComSchool(ComSchoolDto oComSchoolDto) throws Exception {
        List<ComSchool> oComSchoolList = oComSchoolMapper.selectAll();
        //PoToDto
        List<ComSchoolDto> oComSchoolDtoList = (List<ComSchoolDto>) PoToDTO.poToDtoList(oComSchoolList,new ComSchoolDto());
        oComSchoolDtoList.forEach(item->{
            double distance = DistanceUtil.getLatAndLon(item.getLatitude(), item.getLongitude(), oComSchoolDto.getPhoneLatitude(), oComSchoolDto.getPhoneLongitude());
            item.setPhoneDistance(distance);
        });
        //根据手机距离排序
        oComSchoolDtoList.sort((t1,t2) -> t1.getPhoneDistance().compareTo(t2.getPhoneDistance()));
        return Result.ok(oComSchoolDtoList.get(0));
    }

}
